package com.mm.base.quartz.task;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mm.domain.book.DBookSource;
import com.mm.serivce.book.BookInfoService;
import com.mm.serivce.book.BookSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description 电子书定时任务
 * @Date 2023/10/24 下午3:27
 * @Author yanglin
 **/
@Slf4j
@Component
public class BookCrawlingTask {

    private final BookSourceService bookSourceService;
    private final BookInfoService bookInfoService;
    public BookCrawlingTask(BookSourceService bookSourceService, BookInfoService bookInfoService) {
        this.bookSourceService = bookSourceService;
        this.bookInfoService = bookInfoService;
    }

    /**
     * 电子书同步最近更新
     * 每天凌晨2点15执行 0 15 2 ? * *
     */
    public void crawlingLastUpdateBook() {
        LambdaQueryWrapper<DBookSource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DBookSource::getSourceCategory, 100);
        List<DBookSource> bookSourceList = bookSourceService.list(queryWrapper);
        if (CollectionUtil.isEmpty(bookSourceList)) {
            return;
        }
        log.info("crawlingLastUpdateBook start size : {}", bookSourceList.size());
        for (DBookSource bookSource : bookSourceList) {
            bookSourceService.crawlingCategoryBook(bookSource.getSourceId(), 1);
        }
        log.info("crawlingLastUpdateBook end");
    }

    /**
     * 电子书同步
     * 每五十分钟跑一次
     */
    @Scheduled(cron = "* 50 * * * ?")
    public void crawlingAllBook() {
        log.info("Task crawlingAllBook start.");
        bookSourceService.crawlingAllBook(20);
        // 删除最近一天没有更新的记录
        bookInfoService.removeNotUpdateBook();
        log.info("Task crawlingAllBook end.");
    }
}
